﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Context;

namespace Web7.Core.Domain.NHibernate
{
    /// <summary>
    /// NHibernate基类
    /// </summary>
    public class NHibernateBase
    {
        protected readonly ISessionFactory sessionFactory;

        public NHibernateBase(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }

        private ISession session;
        protected virtual ISession Session
        {
            get 
            {
                if (!CurrentSessionContext.HasBind(sessionFactory))
                {
                    CurrentSessionContext.Bind(sessionFactory.OpenSession());
                }
                return sessionFactory.GetCurrentSession();
            }
        }

        protected virtual TResult Transact<TResult>(Func<TResult> func)
        {
            if (!Session.Transaction.IsActive)
            {
                TResult result;
                using (var tx = Session.BeginTransaction())
                {
                    result = func.Invoke();
                    tx.Commit();
                }
                return result;
            }
            return func.Invoke();
        }

        protected virtual void Transact(Action action)
        {
            Transact(() => 
            { 
                action.Invoke(); 
                return true; 
            });
        }
    }
}
